/*
 * Copyright (c) 2005, 2014 vacoor
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 */
package org.vacoor.nothing.common.io;

import java.io.IOException;
import java.io.OutputStream;

/**
 * 多输出流
 *
 * @author vacoor
 */
public class MultiOutputStream extends OutputStream {
    private final OutputStream out1;
    private final OutputStream out2;
    private volatile boolean closed;

    public static MultiOutputStream on(OutputStream out1, OutputStream out2) {
        return new MultiOutputStream(out1, out2);
    }

    public MultiOutputStream(OutputStream out1, OutputStream out2) {
        this.out1 = out1;
        this.out2 = out2;
    }

    @Override
    public void write(int b) throws IOException {
        out1.write(b);
        out2.write(b);
    }

    @Override
    public void write(byte[] b) throws IOException {
        out1.write(b);
        out2.write(b);
    }

    @Override
    public void write(byte[] b, int off, int len) throws IOException {
        out1.write(b, off, len);
        out2.write(b, off, len);
    }

    @Override
    public void flush() throws IOException {
        out1.flush();
        out2.flush();
    }

    @Override
    public void close() throws IOException {
        if (closed) {
            return;
        }
        out1.close();
        out2.close();
        closed = true;
    }
}
